package com.ruoyi.task.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.task.domain.CameraInfo;
import com.ruoyi.task.domain.ChannelConfig;
import com.ruoyi.task.domain.EquipmentChannelConfig;
import com.ruoyi.task.domain.EquipmentConfig;
import com.ruoyi.task.domain.FhPdTaskImportConfig;
import com.ruoyi.task.domain.HyGatherTask;
import com.ruoyi.task.domain.SceneCameraParamsInfo;
import com.ruoyi.task.domain.SubBankServerConfig;
import com.ruoyi.task.domain.TaskDetail;
import com.ruoyi.task.domain.TaskImportConfig;
import com.ruoyi.task.domain.ZhTaskImportConfig;
import com.ruoyi.task.mapper.CameraInfoMapper;
import com.ruoyi.task.mapper.ChannelConfigMapper;

import com.ruoyi.task.service.ISceneParamsInfoService;
import com.ruoyi.task.service.ISubBankServerConfigService;
import com.ruoyi.task.service.ITaskDetailService;
import com.ruoyi.task.service.impl.TaskTypeEveryDayServiceImpl.ServiceResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.task.mapper.EquipmentConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.task.mapper.TaskConfigMapper;
import com.ruoyi.task.domain.TaskConfig;
import com.ruoyi.task.service.ITaskConfigService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * 任务配置配置Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-24
 */
@Service
@Slf4j
public class TaskConfigServiceImpl implements ITaskConfigService {
    @Autowired
    private TaskConfigMapper taskConfigMapper;

    @Autowired
    private ChannelConfigMapper channelConfigMapper;

    @Autowired
    private EquipmentConfigMapper equipmentConfigMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private CameraInfoMapper cameraInfoMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    ITaskDetailService taskDetailService;

    @Autowired
    ISubBankServerConfigService subBankServerConfigService;

    @Autowired
    private ISceneParamsInfoService sceneParamsInfoService;


    /**
     * 查询任务配置配置
     *
     * @param taskConfigId 任务配置配置主键
     * @return 任务配置配置
     */
    @Override
    public TaskConfig selectTaskConfigByTaskConfigId(Long taskConfigId) {
        return taskConfigMapper.selectTaskConfigByTaskConfigId(taskConfigId);
    }

    /**
     * 查询任务配置配置列表
     *
     * @param taskConfig 任务配置配置
     * @return 任务配置配置
     */
    @Override
    public List<TaskConfig> selectTaskConfigList(TaskConfig taskConfig) {

        if (taskConfig.getScenariosType() != null) {
            taskConfig.setScenariosTypeList(
                    StringUtils.str2List(taskConfig.getScenariosType(), ",", true, true));
        }
        return taskConfigMapper.selectTaskConfigList(taskConfig);
    }

    @Override
    public List<TaskConfig> queryTaskConfigList(Integer length, String taskType) {

        return taskConfigMapper.queryTaskConfigList(length, taskType);
    }

    /**
     * 新增任务配置配置
     *
     * @param taskConfig 任务配置配置
     * @return 结果
     */
    @Override
    public int insertTaskConfig(TaskConfig taskConfig) {
        try {
            taskConfig.setCreateTime(DateUtils.getNowDate());
            taskConfig.setUpdateTime(DateUtils.getNowDate());

            // 查询机构
            SysDept sysDept = sysDeptService.selectDeptByCode(taskConfig.getBankCode());

            if (sysDept == null) {
                throw new BaseException("机构信息不存在");
            }

            taskConfig.setBankName(sysDept.getDeptName());
            taskConfig.setSubBankCode(sysDept.getParentCode());
            taskConfig.setSubBankName(sysDept.getParentName());

            if (StringUtils.equals(taskConfig.getTaskType(), "1") || StringUtils.equals(
                    taskConfig.getTaskType(), "3")) {
                if (taskConfig.getSecondMerge() <= 0) {
                    throw new BaseException("分割时间需要大于0");
                }

                // 查询数据库
                CameraInfo cameraInfo = new CameraInfo();
                cameraInfo.setCameraId(taskConfig.getCameraId());
                cameraInfo.setStatus("0");
                cameraInfo = cameraInfoMapper.selectCameraInfo(cameraInfo);
                if (cameraInfo == null) {
                    throw new BaseException("未查询到相应的摄像头数据");
                }
                if (StringUtils.equals(taskConfig.getTaskType(), "3") && (StringUtils.isBlank(
                        cameraInfo.getNvrId()) || StringUtils.isBlank(
                        cameraInfo.getCameraChannel()))) {
                    throw new BaseException("该摄像头未配置录像机编号或通道号，不支持浩云分行模式");
                }
                taskConfig.setChannelRemark(cameraInfo.getCameraName());
                taskConfig.setCameraId(cameraInfo.getCameraId());
            } else {
                // 查询录像机通道信息
                ChannelConfig channelConfig = channelConfigMapper.selectChannelConfigByChannelId(
                        Long.parseLong(taskConfig.getChannelKey()));
                if (channelConfig == null) {
                    throw new BaseException("未查询到相应的通道数据");
                }
                taskConfig.setChannelRemark(channelConfig.getRemark());
                taskConfig.setChannelId(channelConfig.getEquipmentChannel());
            }

            String msg = checkSceneParamConfig(taskConfig);
            if(StringUtils.isNotBlank(msg)){
                throw new BaseException(msg);
            }

            return taskConfigMapper.insertTaskConfig(taskConfig);
        } catch (BaseException ex) {
            throw ex;
        } catch (Exception e) {
            log.error("insertTaskConfig error", e);
            throw new RuntimeException("数据插入异常");
        }
    }

    /**
     * 修改任务配置配置
     *
     * @param taskConfig 任务配置配置
     * @return 结果
     */
    @Override
    public int updateTaskConfig(TaskConfig taskConfig) {
        try {
            taskConfig.setUpdateTime(DateUtils.getNowDate());
            // 查询机构
            SysDept sysDept = sysDeptService.selectDeptByCode(taskConfig.getBankCode());

            if (sysDept == null) {
                throw new BaseException("机构信息不存在");
            }

            taskConfig.setBankName(sysDept.getDeptName());
            taskConfig.setSubBankCode(sysDept.getParentCode());
            taskConfig.setSubBankName(sysDept.getParentName());


            if (StringUtils.equals(taskConfig.getTaskType(), "1") || StringUtils.equals(
                    taskConfig.getTaskType(), "3")) {
                if (taskConfig.getSecondMerge() <= 0) {
                    throw new BaseException("分割时间需要大于0");
                }

                // 查询数据库
                CameraInfo cameraInfo = new CameraInfo();
                cameraInfo.setCameraId(taskConfig.getCameraId());
                cameraInfo.setStatus("0");
                cameraInfo = cameraInfoMapper.selectCameraInfo(cameraInfo);
                if (cameraInfo == null) {
                    throw new BaseException("未查询到相应的摄像头数据");
                }
                if (StringUtils.equals(taskConfig.getTaskType(), "3") && (StringUtils.isBlank(
                        cameraInfo.getNvrId()) || StringUtils.isBlank(
                        cameraInfo.getCameraChannel()))) {
                    throw new BaseException("该摄像头未配置录像机编号或通道号，不支持浩云分行模式");
                }
                taskConfig.setChannelRemark(cameraInfo.getCameraName());
                taskConfig.setCameraId(cameraInfo.getCameraId());
            } else {
                // 查询录像机通道信息
                ChannelConfig channelConfig = channelConfigMapper.selectChannelConfigByChannelId(
                        Long.parseLong(taskConfig.getChannelKey()));
                if (channelConfig == null) {
                    throw new BaseException("未查询到相应的通道数据");
                }
                taskConfig.setChannelRemark(channelConfig.getRemark());
                taskConfig.setChannelId(channelConfig.getEquipmentChannel());
            }

            String msg = checkSceneParamConfig(taskConfig);
            if(StringUtils.isNotBlank(msg)){
                throw new BaseException(msg);
            }

            return taskConfigMapper.updateTaskConfig(taskConfig);
        } catch (BaseException ex) {
            throw ex;
        } catch (Exception e) {
            log.error("updateTaskConfig error ", e);
            throw new RuntimeException("数据插入异常");
        }
    }


    @Override
    public int updateTaskConfigStatus(TaskConfig taskConfig) {
        return taskConfigMapper.updateTaskConfig(taskConfig);
    }

    /**
     * 批量删除任务配置配置
     *
     * @param taskConfigIds 需要删除的任务配置配置主键
     * @return 结果
     */
    @Override
    public int deleteTaskConfigByTaskConfigIds(Long[] taskConfigIds) {
        return taskConfigMapper.deleteTaskConfigByTaskConfigIds(taskConfigIds);
    }

    @Override
    public int updateTaskConfigStatusByIds(Long[] taskConfigIds, String status, String updateBy) {
        return taskConfigMapper.updateTaskConfigStatusByIds(taskConfigIds, status, updateBy);
    }

    /**
     * 删除任务配置配置信息
     *
     * @param taskConfigId 任务配置配置主键
     * @return 结果
     */
    @Override
    public int deleteTaskConfigByTaskConfigId(Long taskConfigId) {
        return taskConfigMapper.deleteTaskConfigByTaskConfigId(taskConfigId);
    }

    @Override
    public boolean importTaskConfig(List<TaskImportConfig> taskImportConfigList, String createBy) {
        List<TaskConfig> taskConfigList = this.checkTaskConfigImport(taskImportConfigList);
        try {
            taskConfigList.forEach(taskConfig -> {
                taskConfig.setTaskType("2");
                taskConfig.setCreateBy(createBy);
                taskConfig.setUpdateBy(createBy);

                taskConfigMapper.insertTaskConfig(taskConfig);
            });
        } catch (BaseException ex) {
            return false;
        }
        return true;
    }

    @Override
    public boolean importZhTaskConfig(List<ZhTaskImportConfig> taskImportConfigList,
            String createBy) {
        List<TaskConfig> taskConfigList = this.checkZhTaskConfigImport(taskImportConfigList);
        try {
            taskConfigList.forEach(taskConfig -> {
                taskConfig.setTaskType("1");
                taskConfig.setCreateBy(createBy);
                taskConfig.setUpdateBy(createBy);

                taskConfigMapper.insertTaskConfig(taskConfig);
            });
        } catch (BaseException ex) {
            log.error("importZhTaskConfig error ", ex);
            return false;
        }
        return true;
    }

    @Override
    public List<FhPdTaskImportConfig> importFhPdTaskConfig(
            List<FhPdTaskImportConfig> taskImportConfigList, String createBy) {

        boolean isError = false;

        for (int i = 0; i < taskImportConfigList.size(); i++) {
            FhPdTaskImportConfig importConfig = taskImportConfigList.get(i);
            try {

                // 去空格
                importConfig.setComputerIp(StringUtils.trim(importConfig.getComputerIp()));
                importConfig.setRegTime(StringUtils.trim(importConfig.getRegTime()));
                importConfig.setBankCode(StringUtils.trim(importConfig.getBankCode()));
                importConfig.setTranCode(StringUtils.trim(importConfig.getTranCode()));

                // 校验数据
                if (StringUtils.isBlank(importConfig.getBankCode())
                        || StringUtils.isBlank(importConfig.getRegTime())
                        || StringUtils.isBlank(importConfig.getComputerIp())
                        || StringUtils.isBlank(importConfig.getTranCode())) {
                    isError = true;
                    importConfig.setMsg("（网点号、交易码、时间或盘点电脑IP地址）参数为空");
                    continue;
                }

                // 判断日期是否合法
                if (!DateUtils.isValidDate(importConfig.getRegTime())) {
                    isError = true;
                    importConfig.setMsg("时间参数不合法（yyyy-MM-dd HH:mm:ss）");
                    continue;
                }

                // 查询机构
                SysDept sysDept = sysDeptService.selectDeptByCode(importConfig.getBankCode());
                if (sysDept == null) {
                    isError = true;
                    importConfig.setMsg("在机构中未找到相应的网点号");
                    continue;
                }

                // 根据数据查询摄像头信息
                EquipmentChannelConfig channelConfig = equipmentConfigMapper.queryEquipmentChannelConfig(
                        importConfig.getBankCode(), importConfig.getComputerIp());
                if (channelConfig == null) {
                    isError = true;
                    importConfig.setMsg("未找到该网点下盘点电脑IP地址的数据（或配置未生效）");
                    continue;
                }

                // 查询字典配置的相关参数
                SysDictData dictData = new SysDictData();
                dictData.setStatus("0");
                dictData.setDictType("pd_tran_code");
                dictData.setDictValue(importConfig.getTranCode());
                List<SysDictData> dictDataList = dictDataMapper.selectDictDataList(dictData);
                if (CollectionUtils.isEmpty(dictDataList)) {
                    isError = true;
                    importConfig.setMsg("pd_tran_code字典中未找到相应的生效配置");
                    continue;
                }

                for (int d = 0; d < dictDataList.size(); d++) {
                    SysDictData dict = dictDataList.get(d);
                    JSONObject json = JSONObject.parseObject(dict.getRemark());
                    // 校验配置
                    if (json == null) {
                        isError = true;
                        importConfig.setMsg("pd_tran_code字典中未找到相应的生效配置");
                        break;
                    } else {
                        if (json.getInteger("startTime") == null
                                || json.getInteger("endTime") == null) {
                            isError = true;
                            importConfig.setMsg(
                                    "pd_tran_code字典中未找到相应的配置（startTime、endTime时间加减分钟）");
                            break;
                        }
                    }


                    int fps = json.getIntValue("fps", 1);
                    Long secondMerge = json.getLongValue("secondMerge", 1);
                    // 取开始与结束时间范围
                    String startTime = DateUtils.addMinutesToDateStr(importConfig.getRegTime(),
                            json.getInteger("startTime"));
                    String endTime = DateUtils.addMinutesToDateStr(importConfig.getRegTime(),
                            json.getInteger("endTime"));

                    // 组装数据
                    TaskConfig taskConfig = new TaskConfig();

                    taskConfig.setEquipmentId(channelConfig.getEquipmentId());
                    taskConfig.setChannelId(channelConfig.getEquipmentChannel());
                    taskConfig.setStartTime(startTime);
                    taskConfig.setStartEnd(endTime);
                    taskConfig.setFps(String.valueOf(fps));
                    taskConfig.setSecondMerge(secondMerge);
                    taskConfig.setScenariosType(StringUtils.split(dict.getDictLabel(), "-")[0]);
                    taskConfig.setFrequencyType("02");
                    taskConfig.setStatus("0");
                    taskConfig.setChannelRemark(channelConfig.getRemark());
                    taskConfig.setBankCode(importConfig.getBankCode());
                    taskConfig.setBankName(sysDept.getDeptName());
                    taskConfig.setSubBankCode(sysDept.getParentCode());
                    taskConfig.setSubBankName(sysDept.getParentName());
                    taskConfig.setTaskType("2");
                    taskConfig.setCreateTime(new Date());
                    taskConfig.setUpdateTime(new Date());
                    taskConfig.setCreateBy(createBy);
                    taskConfig.setUpdateBy(createBy);
                    taskConfig.setEquipmentIp(channelConfig.getEquipmentIp());

                    String msg = checkSceneParamConfig(taskConfig);
                    if(StringUtils.isNotBlank(msg)){
                        isError = true;
                        importConfig.setMsg(msg);
                        break;
                    }

                    int count = taskConfigMapper.insertTaskConfigByParams(taskConfig);
                    if (count <= 0) {
                        isError = true;
                        importConfig.setMsg("已下发过相应的任务");
                    } else {
                        importConfig.setMsg("成功");
                    }
                }

            } catch (Exception e) {
                log.error("importFhPdTaskConfig error", e);
                isError = true;
                importConfig.setMsg("未知异常");
            }
        }
        if (isError) {
            log.info("importFhPdTaskConfig is error params");
            return taskImportConfigList;
        }
        log.info("importFhPdTaskConfig success");
        return null;
    }

    @Override
    public void generateMainTask(TaskConfig taskConfig) {
        try {
            log.info("generateMainTask=== {}", taskConfig);
            // 通过配置信息插入任务明细表
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setSubBankCode(taskConfig.getSubBankCode());
            taskDetail.setSubBankName(taskConfig.getSubBankName());
            taskDetail.setBankCode(taskConfig.getBankCode());
            taskDetail.setBankName(taskConfig.getBankName());

            if (StringUtils.equals("02", taskConfig.getFrequencyType())) {
                taskDetail.setStartTime(taskConfig.getStartTime());
                taskDetail.setStartEnd(taskConfig.getStartEnd());
            } else {
                String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                taskDetail.setStartTime(currentDay + " " + taskConfig.getStartTime());
                taskDetail.setStartEnd(currentDay + " " + taskConfig.getStartEnd());
            }

            taskDetail.setFrequencyType(taskConfig.getFrequencyType());
            taskDetail.setScenariosType(taskConfig.getScenariosType());
            taskDetail.setSecondMerge(taskConfig.getSecondMerge());
            taskDetail.setChannelRemark(taskConfig.getChannelRemark());
            //任务状态（00-初始化 01-视频采集中 02-视频采集完成 03-视频采集失败 04-视频分析中 05-视频分析完成 06-视频分析失败）
            taskDetail.setTaskStatus("00");
            taskDetail.setTaskType(taskConfig.getTaskType());
            taskDetail.setCameraId(taskConfig.getCameraId());
            taskDetailService.insertTaskDetail(taskDetail);


            //将一次性任务下发完,状态改为停用
            if (StringUtils.equals("02", taskConfig.getFrequencyType())) {
                TaskConfig taskConfigUpdate = new TaskConfig();
                taskConfigUpdate.setTaskConfigId(taskConfig.getTaskConfigId());
                taskConfigUpdate.setStatus("1");
                updateTaskConfigStatus(taskConfigUpdate);
            }

        } catch (Exception e) {
            log.error("generateMainTask error ", e);
        }
    }


    @Override
    public void generateBranchHyTask(TaskConfig taskConfig) {
        try {
            log.info("generateBranchHyTask=== {}", taskConfig);
            // 通过配置信息插入任务明细表
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setSubBankCode(taskConfig.getSubBankCode());
            taskDetail.setSubBankName(taskConfig.getSubBankName());
            taskDetail.setBankCode(taskConfig.getBankCode());
            taskDetail.setBankName(taskConfig.getBankName());

            if (StringUtils.equals("02", taskConfig.getFrequencyType())) {
                taskDetail.setStartTime(taskConfig.getStartTime());
                taskDetail.setStartEnd(taskConfig.getStartEnd());
            } else {
                String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                taskDetail.setStartTime(currentDay + " " + taskConfig.getStartTime());
                taskDetail.setStartEnd(currentDay + " " + taskConfig.getStartEnd());
            }

            taskDetail.setFrequencyType(taskConfig.getFrequencyType());
            taskDetail.setScenariosType(taskConfig.getScenariosType());
            taskDetail.setSecondMerge(taskConfig.getSecondMerge());
            taskDetail.setChannelRemark(taskConfig.getChannelRemark());
            //任务状态（00-初始化 01-视频采集中 02-视频采集完成 03-视频采集失败 04-视频分析中 05-视频分析完成 06-视频分析失败）
            taskDetail.setTaskStatus("00");
            taskDetail.setTaskType(taskConfig.getTaskType());
            taskDetail.setCameraId(taskConfig.getCameraId());
            taskDetailService.insertTaskDetail(taskDetail);


            long taskDetailId = taskDetail.getTaskDetailId();

            SubBankServerConfig subBankServerConfig = new SubBankServerConfig();
            subBankServerConfig.setSubBankCode(taskDetail.getSubBankCode());
            List<SubBankServerConfig> subBankServerConfigList = subBankServerConfigService.selectServerConfigList(
                    subBankServerConfig);
            // 采集服务器
            String subServerIp = "";
            if (!CollectionUtils.isEmpty(subBankServerConfigList)) {
                SubBankServerConfig serverConfig = subBankServerConfigList.get(0);
                subServerIp = serverConfig.getServerIp();
            }

            //发送任务接口
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HyGatherTask gatherTask = new HyGatherTask();
            // 生成任务编号
            String taskId = "";
            // 任务类型："capture"(截图) 或 "video"(录像)
            if (taskDetail.getSecondMerge() < 60) {
                gatherTask.setType("video");
                // 2721-1-192.168.1.1-20250812-195731304-(20250812090000-20250812100000)
                // 0256-025600542-20251011-163334938-(20251010100000-20251010110000)
                taskId = String.format("%s-%s-%s-(%s-%s)", taskDetail.getBankCode(),
                        taskDetail.getCameraId(), DateUtils.generateTaskId(),
                        DateUtils.convertToCompactFormat(taskDetail.getStartTime()),
                        DateUtils.convertToCompactFormat(taskDetail.getStartEnd()));
            } else {
                gatherTask.setType("capture");
                // 0256-025600542-20251011-163334938-(20251010100000-20251010110000)
                taskId = String.format("%s-%s-%s-(%s-%s)", taskDetail.getBankCode(),
                        taskDetail.getCameraId(), DateUtils.generateTaskId(),
                        DateUtils.convertToCompactFormat(taskDetail.getStartTime()),
                        DateUtils.convertToCompactFormat(taskDetail.getStartEnd()));
            }
            log.info("generateBranchHyTask taskId = {}", taskId);
            gatherTask.setTaskId(taskId);


            gatherTask.setStartTime(taskDetail.getStartTime());
            gatherTask.setEndTime(taskDetail.getStartEnd());
            gatherTask.setSecondMerge(taskDetail.getSecondMerge());
            gatherTask.setSceneIds(taskConfig.getScenariosType());
            gatherTask.setSubBankCode(taskDetail.getBankCode());

            // 查询NVR ID、通道号
            CameraInfo cameraInfo = new CameraInfo();
            cameraInfo.setCameraId(taskConfig.getCameraId());
            cameraInfo = cameraInfoMapper.selectCameraInfo(cameraInfo);
            if (cameraInfo == null || StringUtils.isBlank(cameraInfo.getNvrId())
                    || StringUtils.isBlank(cameraInfo.getCameraChannel())) {
                TaskDetail taskDetailUpdate = new TaskDetail();
                taskDetailUpdate.setTaskDetailId(taskDetailId);
                taskDetailUpdate.setTaskStatus("03");
                taskDetailService.updateTaskDetail(taskDetailUpdate);
                return;
            }
            gatherTask.setChannelId(cameraInfo.getCameraChannel());
            gatherTask.setVrId(cameraInfo.getNvrId());
            gatherTask.setCameraId(cameraInfo.getCameraId());

            // 4. 创建请求实体
            HttpEntity<HyGatherTask> requestEntity = new HttpEntity<>(gatherTask, headers);
            String branchTaskUrl = "http://" + subServerIp + ":8081" + "/video/hyNvrVideoTask";
            ResponseEntity<ServiceResponse> response = restTemplate.exchange(branchTaskUrl,
                    HttpMethod.POST, requestEntity, ServiceResponse.class);
            log.info("hyNvrVideoTask result = {}", JSONObject.toJSONString(response.getBody()));
            String code = Objects.requireNonNull(response.getBody()).getCode();
            log.info("hyNvrVideoTask result, code:{}", code);
            TaskDetail taskDetailUpdate = new TaskDetail();
            taskDetailUpdate.setTaskDetailId(taskDetailId);
            taskDetailUpdate.setTaskId(taskId);
            taskDetailUpdate.setNvrId(cameraInfo.getNvrId());
            taskDetailUpdate.setEquipmentChannel(cameraInfo.getCameraChannel());

            if ("0".equals(code)) {
                taskDetailUpdate.setTaskStatus("01");

                //将一次性任务下发完,状态改为停用
                if (StringUtils.equals("02", taskConfig.getFrequencyType())) {
                    TaskConfig taskConfigUpdate = new TaskConfig();
                    taskConfigUpdate.setTaskConfigId(taskConfig.getTaskConfigId());
                    taskConfigUpdate.setStatus("1");
                    updateTaskConfigStatus(taskConfigUpdate);
                }
            } else {
                String msg = Objects.requireNonNull(response.getBody()).getMsg();
                taskDetailUpdate.setMsg(msg);
                taskDetailUpdate.setTaskStatus("03");
            }
            taskDetailService.updateTaskDetail(taskDetailUpdate);

        } catch (Exception e) {
            log.error("generateBranchHyTask error ", e);
        }
    }


    private List<TaskConfig> checkTaskConfigImport(List<TaskImportConfig> taskImportConfigList) {
        List<TaskConfig> taskConfigList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        AtomicInteger counter = new AtomicInteger(2);
        taskImportConfigList.forEach(taskImportConfig -> {
            StringBuilder errorMsg = new StringBuilder();
            String equipmentIp = taskImportConfig.getEquipmentIp();
            String channelId = taskImportConfig.getChannelId();
            String bankCode = taskImportConfig.getBankCode();
            String frequencyType = taskImportConfig.getFrequencyType();
            String scenariosType = taskImportConfig.getScenariosType();
            String startTime = taskImportConfig.getStartTime();
            String endTime = taskImportConfig.getStartEnd();
            String fps = taskImportConfig.getFps();
            String secondMergeT = taskImportConfig.getSecondMerge();
            long secondMerge = 0;
            EquipmentConfig equipmentConfigData = null;
            ChannelConfig channelConfigData = null;

            EquipmentConfig equipmentConfig = new EquipmentConfig();
            equipmentConfig.setEquipmentIp(equipmentIp);
            equipmentConfig.setBankCode(bankCode);
            equipmentConfig.setStatus("0");

            List<EquipmentConfig> equipmentConfigList = equipmentConfigMapper.selectEquipmentConfigList(
                    equipmentConfig);
            if (CollectionUtils.isEmpty(equipmentConfigList)) {
                errorMsg.append("网点号：").append(bankCode).append("，录像机：").append(equipmentIp)
                        .append("未配置；");
            } else {
                equipmentConfigData = equipmentConfigList.get(0);
                ChannelConfig channelConfig = new ChannelConfig();
                channelConfig.setEquipmentId(equipmentConfigData.getEquipmentId());
                channelConfig.setEquipmentChannel(channelId);
                channelConfig.setStatus("0");
                List<ChannelConfig> channelConfigList = channelConfigMapper.selectChannelConfigList(
                        channelConfig);
                if (CollectionUtils.isEmpty(channelConfigList)) {
                    errorMsg.append("网点号：").append(bankCode).append("，录像机：")
                            .append(equipmentIp).append("，通道号：").append(channelId)
                            .append("未配置；");
                } else {
                    channelConfigData = channelConfigList.get(0);
                }
            }
            if (StringUtils.isNotEmpty(frequencyType) && !frequencyType.equals("01")
                    && !frequencyType.equals("02")) {
                errorMsg.append("任务频率：").append(frequencyType)
                        .append("不合法，只能为(01-每日)或者(02-单次)；");
            }

            if (StringUtils.isNotEmpty(frequencyType) && frequencyType.equals("01")) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                sdf.setLenient(false); // 严格模式
                try {
                    sdf.parse(startTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为每日，开始日期").append(startTime)
                            .append("不合法，只能为:HH:mm:ss；");
                }
                try {
                    sdf.parse(endTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为每日，结束时间").append(endTime)
                            .append("不合法，只能为:HH:mm:ss；");
                }
            }

            if (StringUtils.isNotEmpty(frequencyType) && frequencyType.equals("02")) {
                SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
                sdf.setLenient(false); // 严格模式
                try {
                    sdf.parse(startTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为单次，开始时间").append(startTime)
                            .append("不合法，只能为:yyyy-MM-dd HH:mm:ss；");
                }
                try {
                    sdf.parse(endTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为单次，结束时间").append(endTime)
                            .append("不合法，只能为:yyyy-MM-dd HH:mm:ss；");
                }
            }

            List<SysDictData> sysDictDataList = dictDataMapper.selectDictDataByType(
                    "task_scenarios_type");
            AtomicReference<String> dictValue = new AtomicReference<>("");
            AtomicReference<String> dictLabelAndValue = new AtomicReference<>("");
            if (!CollectionUtils.isEmpty(sysDictDataList)) {
                sysDictDataList.forEach(sysDictData -> {
                    dictValue.set(dictValue + sysDictData.getDictValue() + ",");
                    dictLabelAndValue.set(dictLabelAndValue + sysDictData.getDictValue() + "-"
                            + sysDictData.getDictLabel() + ",");
                });
            }

            String scenariosTypeStatic = dictValue.toString();
            if (StringUtils.isNotEmpty(scenariosType)) {
                String[] strings = scenariosType.split(",");
                for (String s : strings) {
                    if (!scenariosTypeStatic.contains(s)) {
                        errorMsg.append("应用场景：").append(scenariosType).append("不合法，")
                                .append(dictLabelAndValue.toString());
                    }
                }
            } else {
                errorMsg.append("应用场景：").append(scenariosType).append("不能为空；");
            }

            try {
                secondMerge = Long.parseLong(secondMergeT);
            } catch (NumberFormatException e) {
                errorMsg.append("分割时间：").append(secondMergeT).append("不合法；");
            }

            int row = counter.getAndIncrement();

            // 查询机构
            SysDept sysDept = sysDeptService.selectDeptByCode(bankCode);
            if (sysDept == null) {
                errorMsg.append("网点号：").append(bankCode).append("未配置；");
            }

            TaskConfig taskConfigScene = new TaskConfig();
            taskConfigScene.setEquipmentIp(equipmentIp);
            taskConfigScene.setChannelId(channelId);
            taskConfigScene.setScenariosType(scenariosType);
            taskConfigScene.setTaskType("2");
            taskConfigScene.setBankCode(bankCode);

            String msg = checkSceneParamConfig(taskConfigScene);
            if(StringUtils.isNotBlank(msg)){
                errorMsg.append(msg);
            }

            if (StringUtils.isNotEmpty(errorMsg)) {
                errorList.add("第" + row + "行错误：" + errorMsg + "\n");
            } else {
                TaskConfig taskConfig = new TaskConfig();
                assert equipmentConfigData != null;
                assert sysDept != null;
                taskConfig.setEquipmentId(equipmentConfigData.getEquipmentId());
                taskConfig.setChannelId(channelConfigData.getEquipmentChannel());
                taskConfig.setStartEnd(endTime);
                taskConfig.setScenariosType(scenariosType);
                taskConfig.setStartTime(startTime);
                taskConfig.setFrequencyType(frequencyType);
                taskConfig.setFps(fps);
                taskConfig.setSecondMerge(secondMerge);
                taskConfig.setStatus("0");
                taskConfig.setChannelRemark(channelConfigData.getRemark());
                taskConfig.setBankCode(bankCode);
                taskConfig.setBankName(sysDept.getDeptName());
                taskConfig.setSubBankCode(sysDept.getParentCode());
                taskConfig.setSubBankName(sysDept.getParentName());
                taskConfig.setTaskType("2");
                taskConfig.setCreateTime(new Date());
                taskConfig.setUpdateTime(new Date());
                taskConfigList.add(taskConfig);
            }
        });

        if (!CollectionUtils.isEmpty(errorList)) {
            throw new BaseException(errorList.toString());
        }
        return taskConfigList;
    }


    /**
     * 检查总行任务导入配置
     *
     * @param taskImportConfigList
     * @return
     */
    private List<TaskConfig> checkZhTaskConfigImport(
            List<ZhTaskImportConfig> taskImportConfigList) {
        List<TaskConfig> taskConfigList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        AtomicInteger counter = new AtomicInteger(2);
        taskImportConfigList.forEach(taskImportConfig -> {
            StringBuilder errorMsg = new StringBuilder();
            String bankCode = taskImportConfig.getBankCode();
            String cameraId = taskImportConfig.getCameraId();
            String scenariosType = taskImportConfig.getScenariosType();
            String frequencyType = taskImportConfig.getFrequencyType();
            String startTime = taskImportConfig.getStartTime();
            String endTime = taskImportConfig.getEndTime();
            String secondMergeT = taskImportConfig.getSecondMerge();
            long secondMerge = 0;

            // 检查摄像头是否正确
            CameraInfo cameraInfo = new CameraInfo();
            cameraInfo.setCameraId(cameraId);
            cameraInfo.setDeptCode(bankCode);
            cameraInfo.setStatus("0");
            cameraInfo = this.cameraInfoMapper.selectCameraInfo(cameraInfo);

            if (cameraInfo == null || StringUtils.isBlank(cameraInfo.getCameraName())) {
                errorMsg.append("网点号：").append(bankCode).append("，摄像头ID：").append(cameraId)
                        .append("未配置或未启用；");
            }

            if (StringUtils.isNotEmpty(frequencyType) && !frequencyType.equals("01")
                    && !frequencyType.equals("02")) {
                errorMsg.append("任务频率：").append(frequencyType)
                        .append("不合法，只能为(01-每日)或者(02-单次)；");
            }

            if (StringUtils.isNotEmpty(frequencyType) && frequencyType.equals("01")) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                sdf.setLenient(false); // 严格模式
                try {
                    sdf.parse(startTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为每日，开始日期").append(startTime)
                            .append("不合法，只能为:HH:mm:ss；");
                }
                try {
                    sdf.parse(endTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为每日，结束时间").append(endTime)
                            .append("不合法，只能为:HH:mm:ss；");
                }
            }

            if (StringUtils.isNotEmpty(frequencyType) && frequencyType.equals("02")) {
                SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
                sdf.setLenient(false); // 严格模式
                try {
                    sdf.parse(startTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为单次，开始时间").append(startTime)
                            .append("不合法，只能为:yyyy-MM-dd HH:mm:ss；");
                }
                try {
                    sdf.parse(endTime);
                } catch (ParseException e) {
                    errorMsg.append("任务频率为单次，结束时间").append(endTime)
                            .append("不合法，只能为:yyyy-MM-dd HH:mm:ss；");
                }
            }

            List<SysDictData> sysDictDataList = dictDataMapper.selectDictDataByType(
                    "task_scenarios_type");
            AtomicReference<String> dictValue = new AtomicReference<>("");
            AtomicReference<String> dictLabelAndValue = new AtomicReference<>("");
            if (!CollectionUtils.isEmpty(sysDictDataList)) {
                sysDictDataList.forEach(sysDictData -> {
                    dictValue.set(dictValue + sysDictData.getDictValue() + ",");
                    dictLabelAndValue.set(dictLabelAndValue + sysDictData.getDictValue() + "-"
                            + sysDictData.getDictLabel() + ",");
                });
            }

            String scenariosTypeStatic = dictValue.toString();
            if (StringUtils.isNotEmpty(scenariosType)) {
                String[] strings = scenariosType.split(",");
                for (String s : strings) {
                    if (!scenariosTypeStatic.contains(s)) {
                        errorMsg.append("应用场景：").append(scenariosType).append("不合法，")
                                .append(dictLabelAndValue.toString());
                    }
                }
            } else {
                errorMsg.append("应用场景：").append(scenariosType).append("不能为空；");
            }

            try {
                secondMerge = Long.parseLong(secondMergeT);
                if (secondMerge <= 0) {
                    errorMsg.append("分割时间：").append(secondMergeT).append("必须大于0；");
                }
            } catch (NumberFormatException e) {
                errorMsg.append("分割时间：").append(secondMergeT).append("不合法；");
            }

            int row = counter.getAndIncrement();

            // 查询机构
            SysDept sysDept = sysDeptService.selectDeptByCode(bankCode);
            if (sysDept == null) {
                errorMsg.append("网点号：").append(bankCode).append("未配置；");
            }

            TaskConfig taskConfigScene = new TaskConfig();
            taskConfigScene.setCameraId(cameraId);
            taskConfigScene.setScenariosType(scenariosType);
            taskConfigScene.setTaskType("1");
            taskConfigScene.setBankCode(bankCode);

            String msg = checkSceneParamConfig(taskConfigScene);
            if(StringUtils.isNotBlank(msg)){
                errorMsg.append(msg);
            }

            if (StringUtils.isNotEmpty(errorMsg)) {
                errorList.add("第" + row + "行错误：" + errorMsg + "\n");
            } else {
                TaskConfig taskConfig = new TaskConfig();
                assert cameraInfo != null && StringUtils.isNotBlank(cameraInfo.getCameraName());
                assert sysDept != null;
                taskConfig.setStartEnd(endTime);
                taskConfig.setScenariosType(scenariosType);
                taskConfig.setStartTime(startTime);
                taskConfig.setFrequencyType(frequencyType);
                taskConfig.setSecondMerge(secondMerge);
                taskConfig.setStatus("0");
                taskConfig.setCameraId(cameraInfo.getCameraId());
                taskConfig.setChannelRemark(cameraInfo.getCameraName());
                taskConfig.setBankCode(bankCode);
                taskConfig.setBankName(sysDept.getDeptName());
                taskConfig.setSubBankCode(sysDept.getParentCode());
                taskConfig.setSubBankName(sysDept.getParentName());
                taskConfig.setTaskType("1");
                taskConfig.setCreateTime(new Date());
                taskConfig.setUpdateTime(new Date());
                taskConfigList.add(taskConfig);
            }
        });

        if (!CollectionUtils.isEmpty(errorList)) {
            throw new BaseException(errorList.toString());
        }
        return taskConfigList;
    }


    /**
     * 检查场景参数配置
     * @param taskConfig
     * @return
     */
    private String checkSceneParamConfig(TaskConfig taskConfig){
        String[] scenarioTypeList = taskConfig.getScenariosType().split(",");
        StringBuilder errorMsg = new StringBuilder();

        for (String scene : scenarioTypeList) {
            SceneCameraParamsInfo sceneCameraParams = new SceneCameraParamsInfo();
            sceneCameraParams.setScenariosType(scene);
            sceneCameraParams.setEquipmentChannel(taskConfig.getChannelId());
            sceneCameraParams.setEquipmentIp(taskConfig.getEquipmentIp());
            sceneCameraParams.setCameraId(taskConfig.getCameraId());
            sceneCameraParams.setTaskType(taskConfig.getTaskType());
            sceneCameraParams.setBankCode(taskConfig.getBankCode());
            Map sceneParamsConfig = sceneParamsInfoService.querySceneParamsConfig(
                    sceneCameraParams);
            if (sceneParamsConfig == null) {
                String name = DictUtils.getDictLabel("task_scenarios_type", scene);
                errorMsg.append(String.format("未查询到【%s】相应的场景配置参数;", name));
            }
        }

        return errorMsg.toString();
    }
}
